package cn.org.donald.framework.service.impl;

import cn.org.donald.framework.service.SysDictionaryService;
import cn.org.donald.framework.util.BeanUtil;
import cn.org.donald.framework.util.ListUtil;
import cn.org.donald.mapper.DictionaryMapper;
import cn.org.donald.pojo.entity.system.Dictionary;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Donald
 * @since 2020-11-11
 */
@Service(interfaceClass = SysDictionaryService.class, version = "1.0.0",group = "donald")
public class SysDictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements SysDictionaryService {

    @Autowired
    private DictionaryMapper dictionaryMapper;

    @Override
    public boolean isExistByCode(String code) {
        QueryWrapper<Dictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",code);
        Dictionary dictionary = dictionaryMapper.selectOne(queryWrapper);
        return BeanUtil.isEmptyOrClassFieldAllEmpty(dictionary);
    }

    @Transactional
    @Override
    public boolean removeAndChild(Long id) {
        // 查询code
        Dictionary dictionaryFromDB = this.getById(id);
        // 查询是否存在子字典
        QueryWrapper<Dictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_code",dictionaryFromDB.getCode());
        List<Dictionary> dictionaries = dictionaryMapper.selectList(queryWrapper);
        // 存在子字典,全部删除
        if (!ListUtil.isEmptyOrHasClassFieldAllEmpty(dictionaries)){
            List<Long> ids = new ArrayList<>();
            dictionaries.forEach(dictionary -> ids.add(dictionary.getId()));
            this.removeByIds(ids);
        }
        return this.removeById(id);
    }

    @Override
    public List<Dictionary> getListByParentCode(String parentCode) {
        QueryWrapper<Dictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_code",parentCode);
        return super.list(queryWrapper);
    }

    @Override
    public List<Dictionary> getParentList() {
        QueryWrapper<Dictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("parent_code");
        return super.list(queryWrapper);
    }

}
